package com.smartalarmclock.UI;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;
import java.util.Set;

import android.view.View;
import android.view.View.OnClickListener;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import com.smartalarmclock.Logic.AcManager;
import com.smartalarmclock.Model.ILogEntry;
import com.smartalarmclock.Model.LogEntryFactory;
import com.smartalarmclock.Model.Exceptions.DataEntityDoesNotExistException;
import com.smartalarmclock.Model.Exceptions.InvalidDeleteDataEntityOperationException;
import com.smartalarmclock.Model.Exceptions.InvalidSaveDataEntityOperationException;
import com.smartalarmclock.UI.R;

public class HistoryActivity extends Activity {
	
	public final static String EXTRA_MESSAGE = "com.smartalarmclock.UI.MESSAGE";
	private ArrayList<LogListItem> m_ListLogs = new ArrayList<LogListItem>();
	private ListView m_ListViewLog;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		Log.v("History Activity", "Start");
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.log_list);
		
		m_ListLogs = GetSearchResults(getIntent().getIntExtra("CONTACT_ID", 0));
		
        // set listener for buttons
        final Button clearLogButton = (Button)findViewById(R.id.buttonClearSelectedLogs);
        clearLogButton.setOnClickListener(clearLogListener);
		
        // set profile list adapter and items on-click listener
        m_ListViewLog = (ListView) findViewById(R.id.log_list);
        m_ListViewLog.setAdapter(new LogListAdapter(this, m_ListLogs));
        m_ListViewLog.setOnItemClickListener(logListItemClickListener);
	}
	
	
    @Override
    protected void onResume()
    {
    	super.onResume();
    	// update the active profiles from the AcManager
  		final ListView logListView = (ListView) findViewById(R.id.log_list);
        ArrayAdapter<LogListItem> arrayAdapter = (ArrayAdapter<LogListItem>)logListView.getAdapter();
		arrayAdapter.notifyDataSetChanged();
    }
	
	
	private OnItemClickListener logListItemClickListener = new OnItemClickListener() {
		@Override
    	public void onItemClick(AdapterView<?> a, View v, int position, long id) {
		    String logMessage = m_ListLogs.get(position).getLogMsg();
		    Intent logDetailsintent = new Intent(HistoryActivity.this, LogItemDetailsActivity.class);
		    logDetailsintent.putExtra(EXTRA_MESSAGE, logMessage); 
    		Log.v("startActivity(logDetailsintent);", "Start");
      		startActivity(logDetailsintent);
    		Log.v("startActivity(logDetailsintent);", "Finish");
      		
    		/*Object o = m_ListViewLog.getItemAtPosition(position);
        	LogListItem obj_itemDetails = (LogListItem)o;
    		Toast.makeText(HistoryActivity.this, "You have chosen : " + " " 
        	+ obj_itemDetails.getLogMsg(), Toast.LENGTH_LONG).show();*/
		}
	};
 
		
	private OnClickListener clearLogListener = new OnClickListener()
	{
    	@Override
        public void onClick(View v)
        {   
    		ArrayList<LogListItem> tmpListLogs = new ArrayList<LogListItem>();
    		tmpListLogs = (ArrayList<LogListItem>) m_ListLogs.clone();
    		LogEntryFactory logEntryFactory = new LogEntryFactory();
    		StringBuffer responseText = new StringBuffer();  
    		ILogEntry logEntry;
			 for(LogListItem log: tmpListLogs){
				 if(log.isSelected()){
					 try {
						 logEntry = logEntryFactory.GetLogEntryById(getApplicationContext(), log.getId());
						 logEntry.Delete(getApplicationContext());
					} catch (DataEntityDoesNotExistException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (InvalidDeleteDataEntityOperationException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (InvalidSaveDataEntityOperationException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					 m_ListLogs.remove(log);
				}  
			}
			 refresh();
		 }
    };
    
    private void refresh()
    {
  		final ListView logListView = (ListView) findViewById(R.id.log_list);
        ArrayAdapter<LogListItem> arrayAdapter = (ArrayAdapter<LogListItem>)logListView.getAdapter();
		arrayAdapter.notifyDataSetChanged();
    }
    


    
	private ArrayList<LogListItem> GetSearchResults(int contactId) {
		final ArrayList<LogListItem> results = new ArrayList<LogListItem>();
		AcManager acManager = new AcManager();
		ILogEntry logEntry;
		Set<ILogEntry> logEntries = acManager.GetLogEntries(getApplicationContext(), contactId);
		Iterator<ILogEntry> logIterator = logEntries.iterator();
		String logText;
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yy HH:mm");
		
		while (logIterator.hasNext()) {
			logEntry = logIterator.next();
			logText = simpleDateFormat.format(logEntry.GetTimestamp());
			if (logEntry.GetEvent() == ILogEntry.PhoneEvent.IncomingCall) {
				if (contactId > 0) {
					logText = logText + " - Called";
				} else {
					logText = logText + " - " + logEntry.GetContactName(getApplicationContext()) + " called";
				}
			} else if (logEntry.GetEvent() == ILogEntry.PhoneEvent.SMSMessage) {
				if (contactId > 0) {
					logText = logText + " - Sent SMS";
				} else {
					logText = logText + " - " + logEntry.GetContactName(getApplicationContext()) + " sent SMS";
				}
			}
			LogListItem logItem = new LogListItem(logEntry.GetContactName(getApplicationContext()), logText, logEntry.GetId());
			logItem.setLogMsg(logEntry.GetSentSMSMessageString());
			results.add(logItem);
		}
		
    	return results;
    }
	
}

